package com.cqc.lite.utils;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
        </dependency>
 **/
public class JavaCSVUtil {

    //字符集： UTF-8  GBK
    public static String charsetName = "UTF-8";
    //分隔符
    public static String delimiterString = ",";
    public static char delimiterChar = ',';

    /**
     * 生成CSV文件并保存在指定目录  File csvFile = new File(filename);
     * @param head       文件头
     * @param dataList   数据列表
     * @param fileDir 文件输出路径
     * @param filename   文件名  xx.csv
     */
    public static void createCSVFile(String[] head , List<String[]> dataList, String fileDir, String filename) {
        CsvWriter writer = null;
        try {
            String filePath = fileDir + File.separator + filename;
            writer = new CsvWriter(filePath, delimiterChar, StandardCharsets.UTF_8);
//            writer.setForceQualifier(true);//强制使用限定符
//            writer.setUseTextQualifier(true);
//            writer.setTextQualifier('\t');//会在文本前后都加\t,使字符串的长度是8的整数倍
            writer.writeRecord(head);//写入头
            //写入数据
            for (String[] arr : dataList) {
                writer.writeRecord(arr);
            }
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(writer);
        }
    }

    /**
     *
     * @param filePath  文件名或路径
     */
    public static List<String[]>  readCsv(String filePath){
        List<String[]> list = new ArrayList<>();
        CsvReader reader = null;
        try {
            reader = new CsvReader(filePath,delimiterChar,StandardCharsets.UTF_8);
            reader.readHeaders();//去掉头
            while(reader.readRecord()){
                String rawRecord = reader.getRawRecord();
                //也可以根据列索引和名称读取单元格数据
//                String useranme = reader.get(0);
//                String useranme = reader.get("username");
                String[] arr = rawRecord.split(delimiterString);
                list.add(arr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(reader);
        }
        return list;
    }
    /**
     *
     * @param multipartFile  前端上传的文件
     */
    public static List<String[]>  readCsv(MultipartFile multipartFile){
        List<String[]> list = new ArrayList<>();
        CsvReader reader = null;
        try {
            reader = new CsvReader(multipartFile.getInputStream(),delimiterChar ,StandardCharsets.UTF_8);
            reader.readHeaders();//去掉头
            while(reader.readRecord()){
                String rawRecord = reader.getRawRecord();//读取一行数据
                String[] arr = rawRecord.split(delimiterString);
                list.add(arr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(reader);
        }
        return list;
    }

    private static void close(CsvWriter writer) {
        if (null != writer) {
            try {
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private static void close(CsvReader reader) {
        if (null != reader) {
            try {
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出csv文件
     * @param headList     文件头
     * @param dataList 数据列表
     * @param fileName xx.csv
     */
    public static void downloadCsv(HttpServletRequest request, HttpServletResponse response,
                                   String[] headList, List<String[]> dataList, String fileName) {
        //设置下载的响应头信息
        response.setCharacterEncoding(charsetName);
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        String mimeType = request.getSession().getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);

        CsvWriter writer = null;
        try {
            writer = new CsvWriter(response.getOutputStream(), delimiterChar, StandardCharsets.UTF_8);
            writer.writeRecord(headList);//写入头
            //写入数据
            for (String[] arr : dataList) {
                writer.writeRecord(arr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(writer);
        }
    }



    //----------------------------------test------------------------------

    public static void main(String[] args)  {
        String fileDir = "C:\\Users\\cui\\Desktop";
        String filename = "javaCSV5.csv";
        String[] head = new String[]{"第一列","第二列","第三列"};
        List<String[]> dataList = new ArrayList< String[]>();
        dataList.add(new String[]{"山东","广东","浙江"});
        dataList.add(new String[]{"4","5","6"});

        createCSVFile(head,dataList,fileDir,filename);

        String filePath = fileDir + File.separator + filename;
        List<String[]> list = readCsv(filePath);
        for (String[] arr : list) {
            System.out.println(Arrays.toString(arr));
        }

    }


}
